//
//  HWHomeInformationVC.swift
//  HWanGame
//
//  Created by Apple on 2024/8/1.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit
import Stevia

private let headerID    = "HWHomeInfoTopCateView"

class HWHomeInformationVC: HWBaseViewController {

    private var titleLabel = c_make_ex(UILabel.self)
        .text("推荐").font(17.font_semiBold).color("#17181A").end()
    private var dianImage = c_make_ex(UIImageView.self)
        .image("segement_dian").mode(.scaleAspectFill).end()
    private let searchButton = UIIconButton(style: .leading(itemSpace: 0))
    var pageIndex = 1
    var cateId = 0
    var httpManager = HWHomeHttpManager()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.rowHeight = 102*widthScale
        tableView.register(HWHomeInformationCell.self, forCellReuseIdentifier: "HWHomeInformationCell")
        tableView.register(HWHomeInfoTopCateView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        return tableView
    }()
    private var topView = HWHomeInfoTopView()
    
    var cateModel:[HWHomeInfoCateModel]?
    var model:[HWHomeInfoItemModel]?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        loadCateData()
        addRefresh()
    }

    private func initUI(){
        
        navigationView.isHidden = true
        view.backgroundColor = .colorWithHexString(hexString: "#F7F8FA")
        
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }

        searchButton.style { v in
            v.iconSize = CGSize(width: 16*widthScale, height: 16*widthScale)
            v.setImage("homeSearchLogo".toImage, for: .normal)
            v.setTitle("请输入关键进行搜索", for: .normal)
            v.setTitleColor("#AEB0B3".toColor, for: .normal)
            v.contentEdgeInsets = UIEdgeInsets(top: 7, left: 6, bottom: 0, right: 0)
            v.titleLabel?.font = 12.font_medium
            v.contentHorizontalAlignment = .leading
            v.addTarget(self, action: #selector(searchButtonClick), for: .touchUpInside)
            v.backgroundColor = "#EDEEF0".toColor
            v.layer.cornerRadius = 15*widthScale
            v.layer.masksToBounds = true
        }
        
        view.subviews{
            titleLabel
            dianImage
            searchButton
            tableView
        }
//        tableView.snp.makeConstraints { make in
//            make.edges.equalToSuperview()
//        }
        titleLabel.leading(15*widthScale).top(.statusHeight+10*widthScale)
        dianImage.size(13*widthScale)
        dianImage.CenterX == titleLabel.CenterX
        dianImage.Top == titleLabel.Bottom - 3
        searchButton.trailing(12*widthScale).top(.statusHeight+8*widthScale).width(280*widthScale).height(30*widthScale)
        tableView.leading(0).trailing(0).top(.navi_height).bottom(0)
        
        
        topView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 170*widthScale)
        tableView.tableHeaderView = topView
    }
    
    @objc func searchButtonClick() {
        let searchController = HWSearchController()
        searchController.modalPresentationStyle = .overFullScreen
        self.present(searchController, animated: true, completion: nil)
    }
}

//MARK: data
extension HWHomeInformationVC {
    
    private func loadCateData(){
        
        httpManager.getHomeInfoCate { models in
            
            self.pageIndex = 1
            self.cateId = models[0].id
            let tempModels = models
            tempModels[0].isSel = true
            self.cateModel = tempModels
            self.loadData()
        } failure: { errorStr in
            
        }
    }
    
    private func loadData() {
        tableView.mj_footer?.endRefreshing()
        httpManager.getHomeInfoList(class_id: cateId, p: pageIndex) { infoModel in
            self.tableView.mj_header?.endRefreshing()
            self.model = infoModel.infoData
            self.topView.bannarModel = infoModel.banners
            self.tableView.reloadData()
        } failure: { error in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }

    }
    
    private func addRefresh() {
        
        tableView.mj_header = MJRefreshNormalHeader()
        tableView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        tableView.mj_footer = MJRefreshBackNormalFooter()
        tableView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
    }
    
    
    @objc private func loadNewData() -> () {
        self.pageIndex = 1
        loadData()
    }
    
    @objc private func loadMoreData(){
        self.pageIndex += 1
        httpManager.getHomeInfoList(class_id: cateId, p: pageIndex) { infoModel in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            if (infoModel.infoData?.count ?? 0) > 0 {
                for mod in (infoModel.infoData)! {
                    self.model?.append(mod)
                }
            } else {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            self.tableView.reloadData()
        } failure: { error in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension HWHomeInformationVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return model?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "HWHomeInformationCell", for: indexPath) as! HWHomeInformationCell
        cell.model = model?[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let detailVC = HWHomeInfoDetailVC()
        detailVC.infoId = model?[indexPath.row].id ?? 0
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! HWHomeInfoTopCateView
        header.model = cateModel
        header.updateCateData = { cateID in
            self.cateId = cateID
            self.loadNewData()
        }
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 50*widthScale
    }
}

//extension HWHomeInformationVC:JXSegmentedListContainerViewListDelegate {
//    func listView() -> UIView {
//        return view
//    }
//}

